'use strict';
const sendToWormhole = require('stream-wormhole');
const Controller = require('egg').Controller;
const fs = require('fs');
const path = require('path');

class VdmanagerController extends Controller {
  async upload() {
    const ctx = this.ctx;
    const stream = await ctx.getFileStream();
    const fileName = stream.filename;
    let target  = path.join(`/Users/zhengyingya/Workspace/win/red5-server/webapps/vod/${stream.filename}`);
    const result = await new Promise((resolve, reject) => {
        const remoteFileStream = fs.createWriteStream(target);
        stream.pipe(remoteFileStream);
        let errFlag;
        remoteFileStream.on('error', err => {
            errFlag = true;
            sendToWormhole(stream);
            remoteFileStream.destroy();
            reject(err);
        });
        
        remoteFileStream.on('finish', async () => {
            if (errFlag) return;
            resolve({ fileName, name: stream.fields.name });
        });
      });

      this.ctx.body = {
        code: 1,
        msg: 'ok',
        data: {
          video_url: `http://localhost:5080/vod/${result.fileName}`,
          video_name: result.fileName
        }
      };  
  }


  async add () {
    const ctx = this.ctx;
    const { author, name, date, pressure, simple_name, stress_time, video_url, video_name } = this.ctx.request.body;
    const ret = await this.ctx.model.VideoManage.create({ 
      author, 
      name, 
      date, 
      pressure, 
      simple_name, 
      stress_time,
      video_url,
      video_name
    })

    this.ctx.body = {
      code: 1,
      msg: 'ok',
      data: ret
    };
  }

  async update () {
    const { _id, author, name, date, pressure, simple_name, stress_time, video_url, video_name } = this.ctx.request.body;
    const ret = await this.ctx.model.VideoManage.updateOne(
      {
        _id
      },
      { 
        author, 
        name, 
        date, 
        pressure, 
        simple_name, 
        stress_time,
        video_url,
        video_name
      }
    )
    this.ctx.body = {
      code: 1,
      msg: 'ok'
    };
  }

  async remove () {
    const { _id } = this.ctx.request.body;
    const ret = await this.ctx.model.VideoManage.remove({
      _id
    })
    this.ctx.body = {
      code: 1,
      msg: 'ok'
    };
  }

  async getList () {
    const { pageNo = 1, name = '', simple_name = '', author = '', date = '' } = this.ctx.query;
    let keys = {}
    if (name != '') {
      keys['name'] = {$regex: name}
    }
    if (simple_name != '') {
      keys['simple_name'] = {$regex: simple_name}
    }
    if (author != '') {
      keys['author'] = {$regex: author}
    }
    if (date != '') {
      keys['date'] = {$regex: date}
    }
    console.log(']]]]]]]', keys)
    const allRes = await this.ctx.model.VideoManage.find(keys)
    .skip((pageNo - 1) * 10)
    .limit(10)
    .sort({ _id: "-1" });

    const count = await this.ctx.model.VideoManage.find(keys).count()
    this.ctx.body = {
      code: 1,
      msg: 'ok',
      data: {
        data: allRes,
        pageNo: Number(pageNo),
        totalCount: count
      }
    };
  }

  async getMemberList () {
    const { pageNo = 1, name = '', username = '' } = this.ctx.query;
    let keys = {}
    if (name != '') {
      keys['name'] = {$regex: name}
    }
    if (username != '') {
      keys['username'] = {$regex: username}
    }
    const allRes = await this.ctx.model.Member.find(keys)
    .skip((pageNo - 1) * 10)
    .limit(10)
    .sort({ _id: "-1" });

    const count = await this.ctx.model.Member.find({}).count()
    this.ctx.body = {
      code: 1,
      msg: 'ok',
      data: {
        data: allRes,
        pageNo: Number(pageNo),
        totalCount: count
      }
    };
  }

  async addMember () {
    const ctx = this.ctx;
    const { name, username, gender, jobtitle } = this.ctx.request.body;
    const ret = await this.ctx.model.Member.create({ 
      username, 
      name, 
      gender, 
      jobtitle
    })

    this.ctx.body = {
      code: 1,
      msg: 'ok',
      data: ret
    };
  }

  async updateMember () {
    const { _id, name, username, gender, jobtitle } = this.ctx.request.body;
    const ret = await this.ctx.model.Member.updateOne(
      {
        _id
      },
      {
        name, 
        username, 
        gender, 
        jobtitle
      }
    )
    this.ctx.body = {
      code: 1,
      msg: 'ok'
    };
  }

  async removeMember () {
    const { _id } = this.ctx.request.body;
    const ret = await this.ctx.model.Member.remove({
      _id
    })
    this.ctx.body = {
      code: 1,
      msg: 'ok'
    };
  }
}

module.exports = VdmanagerController;
